package com.home.common.utils.id;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description: 订单号生成/id生成器
 * Created by 王大宸 on 2020-09-25 9:19
 * Created with IntelliJ IDEA.
 */
public class IdUtil {
    private static final Logger logger = LoggerFactory.getLogger(IdUtil.class);

    private static final ZoneId ZONE_ID = ZoneId.of("Asia/Shanghai");
    private static final AtomicInteger SEQ = new AtomicInteger(1000);
    private static final DateTimeFormatter DF_FMT_PREFIX = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSS");
    private volatile static String IP_SUFFIX = null;

    public static String getId() {
        LocalDateTime dataTime = LocalDateTime.now(ZONE_ID);
        if (SEQ.intValue() > 9990) {
            SEQ.getAndSet(1000);
        }
        return dataTime.format(DF_FMT_PREFIX) + getLocalIpSuffix() + SEQ.getAndIncrement();
    }

    private static String getLocalIpSuffix() {
        if (null != IP_SUFFIX) {
            return IP_SUFFIX;
        }
        try {
            synchronized (IdUtil.class) {
                if (null != IP_SUFFIX) {
                    return IP_SUFFIX;
                }
                InetAddress addr = InetAddress.getLocalHost();
                String hostAddress = addr.getHostAddress();
                if (null != hostAddress && hostAddress.length() > 4) {
                    String ipSuffix = hostAddress.trim().split("\\.")[3];
                    if (ipSuffix.length() == 2) {
                        IP_SUFFIX = ipSuffix;
                        return IP_SUFFIX;
                    }
                    ipSuffix = "0" + ipSuffix;
                    IP_SUFFIX = ipSuffix.substring(ipSuffix.length() - 2);
                    return IP_SUFFIX;
                }
                IP_SUFFIX = RandomUtils.nextInt(10, 20) + "";
                return IP_SUFFIX;
            }
        } catch (Exception e) {
            logger.error("获取ip失败:", e);
            IP_SUFFIX = RandomUtils.nextInt(10, 20) + "";
            return IP_SUFFIX;
        }
    }


//    public static void main(String[] args) {
//        for (int i = 0; i < 20; i++) {
//            String s = getId();
//            System.err.println(s);
//        }
//
//        List<String> orderNos = Collections.synchronizedList(new ArrayList<String>());
//        IntStream.range(0, 8000).parallel().forEach(i -> {
//            orderNos.add(getId());
//        });
//
//        List<String> filterOrderNos = orderNos.stream().distinct().collect(Collectors.toList());
//        System.out.println("订单样例：" + orderNos.get(22));
//        System.out.println("生成订单数：" + orderNos.size());
//        System.out.println("过滤重复后订单数：" + filterOrderNos.size());
//        System.out.println("重复订单数：" + (orderNos.size() - filterOrderNos.size()));
//    }

}
